package com.mk.admin.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.mk.admin.mapper.PayOrderMapper;
import com.mk.admin.model.ResultDto;
import com.mk.admin.model.dto.PatientRegisterBudgetDto;
import com.mk.admin.model.dto.PatientRegisterSettlementDto;
import com.mk.admin.model.dto.PayOrderDto;
import com.mk.admin.model.entity.PayOrderEntity;
import com.mk.admin.model.vo.*;
import com.mk.admin.service.PayOrderService;
import com.mk.admin.service.PayService;
import com.mk.admin.service.WeChatPayService;
import com.mk.admin.util.DateTool;
import com.mk.admin.util.HttpTool;
import com.mk.admin.util.JSONCopy;
import com.mk.admin.util.NumberTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PayOrderServiceImpl implements PayOrderService {
    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private WeChatPayService weChatPayService;
    @Autowired
    private PayService payService;

    @Override
    public ResultDto select(PayOrderVo payOrderVo) {
        PayOrderEntity entity = JSONCopy.copy(payOrderVo, PayOrderEntity.class);
        List<PayOrderDto> list = payOrderMapper.select(entity);
        for (PayOrderDto dto : list
        ) {

        }
        return ResultDto.data(payOrderMapper.count(entity), list);
    }

    /**
     * 只更新数据不调用远程
     *
     * @param vo
     * @return
     */
    @Override
    public ResultDto payStatus(PayOrderVo vo) {
        PayOrderEntity entity = JSONCopy.copy(vo, PayOrderEntity.class);
        entity.setPayMoney(NumberTool.strToMoney(vo.getPayMoney()));
        entity.setUpdateTime(DateTool.format());
        return ResultDto.data(payOrderMapper.updateById(entity));
    }

    /**
     * 自助开单处方退款
     *
     * @param vo
     * @return
     */
    @Override
    public ResultDto refund(PayOrderVo vo) {
        PatientRegisterRefundVo patientRegisterRefundVo = getPatientRegisterRefund(vo);
        JSONObject jsonObject = HttpTool.postJson("stt_0007", patientRegisterRefundVo);
        Object result = jsonObject.get("result");
        if (result == null || "[]".equals(result)) {
            return ResultDto.data("error", result);
        }
//            退费成功，修改支付订单，退费到微信
//            微信退款
        JSONObject wechatPayRefund = wechatPayRefund(vo);
        Object resultRefund = wechatPayRefund.get("result");
        if (resultRefund == null || "[]".equals(resultRefund)) {
            return ResultDto.data("error", resultRefund);
        }
//        微信查询
        JSONObject wechatPayRefundSelect = wechatPayRefundSelect(vo);
        Object resultResultSelect = wechatPayRefundSelect.get("result");
        if (resultResultSelect == null || "[]".equals(resultResultSelect)) {
            return ResultDto.data("error", resultResultSelect);
        }
        //        修改订单表状态
        PayOrderEntity payOrderEntity = new PayOrderEntity();
        payOrderEntity.setId(vo.getId());
        payOrderEntity.setPayStatus(vo.getPayStatus());
        payOrderEntity.setPayStatusName(vo.getPayStatusName());
        payOrderEntity.setUpdateTime(DateTool.format());
        payOrderMapper.updateById(payOrderEntity);
        return ResultDto.data("success", "更新成功");
    }

    @Override
    public ResultDto patientRefund(PayOrderVo vo) {
//       先退号stt_0007
        JSONObject jsonObject0007 = getPatientRegisterReturnNoJson(vo);
        Object result0007 = jsonObject0007.get("result");
        if (result0007 == null || "[]".equals(result0007)) {
            return ResultDto.data("error", jsonObject0007);
        }
//        得到退款收据号
        JSONObject jsonObjectReturn0007 = JSONObject.parseObject(result0007.toString());
        vo.setReceiptNo(jsonObjectReturn0007.get("receiptNo") + "");
//        退费stt_0006，挂号不需要调用，只有处方退费调用
//        paySourceType==1表示处方缴费
        if (vo.getPaySourceType() == 1) {
            JSONObject jsonObject0006 = getPatientRegisterReturnMoneyJson(vo);
            Object result0006 = jsonObject0006.get("result");
            if (result0006 == null || "[]".equals(result0006)) {
                return ResultDto.data("error", jsonObject0006);
            }
        }

//        微信退费pay_0327
        JSONObject jsonObject0327 = wechatPayRefund(vo);
        Object result0327 = jsonObject0327.get("result");
        if (result0327 == null || "[]".equals(result0327)) {
            return ResultDto.data("error", jsonObject0327);
        }
//        微信退费查询pay_0328
        JSONObject jsonObject0328 = wechatPayRefundSelect(vo);
        Object result0328 = jsonObject0328.get("result");
        if (result0328 == null || "[]".equals(result0328)) {
            return ResultDto.data("error", jsonObject0328);
        }
//        得到退款流水号
        JSONObject jsonObjectReturn0328 = JSONObject.parseObject(result0328.toString());
        vo.setRefundSerialNo(jsonObjectReturn0328.get("refundId") + "");
        //  退费查询stt_0008,
        //  需要得到stt_0007的退款收据号
        //  需要得到pay_0328退款流水号
        if (vo.getPaySourceType() == 1) {
            JSONObject jsonObject0008 = getPatientRegisterReturnMoneyResultJson(vo);
            Object result0008 = jsonObject0008.get("result");
            if (result0008 == null || "[]".equals(result0008)) {
                return ResultDto.data("error", jsonObject0008);
            }
        }

//        修改订单表状态
        PayOrderEntity payOrderEntity = new PayOrderEntity();
        payOrderEntity.setId(vo.getId());
        payOrderEntity.setPayStatus(vo.getPayStatus());
        payOrderEntity.setPayStatusName(vo.getPayStatusName());
        payOrderEntity.setUpdateTime(DateTool.format());
        payOrderMapper.updateById(payOrderEntity);
        return ResultDto.data("success", "退款成功");
    }

    private JSONObject getPatientRegisterReturnMoneyResultJson(PayOrderVo vo) {
        PatientRegisterReturnMoneyResultVo patientRegisterReturnMoneyResultVo = new PatientRegisterReturnMoneyResultVo();
        int type = vo.getPaySourceType();
//        退款类型 1预约挂号，2处方缴费
        if (type == 1) {
            patientRegisterReturnMoneyResultVo.setRefundType("2");
        } else if (type == 4) {
            patientRegisterReturnMoneyResultVo.setRefundType("1");
        }
//        退款流水号 应为支付的唯一流水号，银行退款成功后返回，用于对账
        patientRegisterReturnMoneyResultVo.setRefundSerialNo(vo.getRefundSerialNo());
        patientRegisterReturnMoneyResultVo.setPaySerialNo(vo.getPaySerialNo());
        patientRegisterReturnMoneyResultVo.setReceiptNo(vo.getRefundReceiptNo());
        patientRegisterReturnMoneyResultVo.setPatId(vo.getPatId());
        patientRegisterReturnMoneyResultVo.setRefundMoney(vo.getPayMoney());
        return payService.patientRegisterReturnMoneyResultJson(patientRegisterReturnMoneyResultVo);
    }

    /**
     * 退费stt_0006
     *
     * @param vo
     * @return
     */
    private JSONObject getPatientRegisterReturnMoneyJson(PayOrderVo vo) {
        PatientRegisterReturnMoneyVo patientRegisterReturnMoneyVo = new PatientRegisterReturnMoneyVo();
        patientRegisterReturnMoneyVo.setPatId(vo.getPatId());
        patientRegisterReturnMoneyVo.setReceiptNo(vo.getReceiptNo());
        patientRegisterReturnMoneyVo.setTotalAmount(vo.getTotalAmount());
        patientRegisterReturnMoneyVo.setRefundMoney(vo.getPayMoney());
        patientRegisterReturnMoneyVo.setPayType(vo.getPayType() + "");
        patientRegisterReturnMoneyVo.setPayMoney(vo.getPayMoney());
        return payService.patientRegisterReturnMoneyJson(patientRegisterReturnMoneyVo);
    }

    /**
     * 退号 stt_0007
     *
     * @param vo
     * @return
     */
    private JSONObject getPatientRegisterReturnNoJson(PayOrderVo vo) {
        PatientRegisterReturnNoVo patientRegisterReturnNoVo = new PatientRegisterReturnNoVo();
        patientRegisterReturnNoVo.setPatId(vo.getPatId());
        patientRegisterReturnNoVo.setReceiptNo(vo.getReceiptNo());
        patientRegisterReturnNoVo.setTotalAmount(vo.getTotalAmount());
        patientRegisterReturnNoVo.setRefundMoney(vo.getPayMoney());
        patientRegisterReturnNoVo.setPayType(vo.getPayType() + "");
        return payService.patientRegisterReturnNoJson(patientRegisterReturnNoVo);
    }

    /**
     * 微信退款查询
     *
     * @param vo
     */
    private JSONObject wechatPayRefundSelect(PayOrderVo vo) {
        WeChatRefundSelectVo weChatRefundSelectVo = new WeChatRefundSelectVo();
        weChatRefundSelectVo.setOrderId(vo.getPayOrderNo());
        return weChatPayService.refundSelectJson(weChatRefundSelectVo);
    }

    /**
     * 微信退款
     *
     * @param vo
     */
    private JSONObject wechatPayRefund(PayOrderVo vo) {
        WeChatRefundVo weChatRefundVo = new WeChatRefundVo();
        weChatRefundVo.setOrderId(vo.getPayOrderNo());
        weChatRefundVo.setRequestSn(vo.getPayOrderNo());
        weChatRefundVo.setRefundMoney(vo.getPayMoney());
        weChatRefundVo.setPayMoney(vo.getPayMoney());
        weChatRefundVo.setRefundDesc(vo.getPayStatusName());
//            微信退款
        return weChatPayService.refundJson(weChatRefundVo);
    }

    private PatientRegisterRefundVo getPatientRegisterRefund(PayOrderVo vo) {
        PatientRegisterRefundVo refundVo = new PatientRegisterRefundVo();
        refundVo.setPatId(vo.getPatId());
        refundVo.setReceiptNo(vo.getReceiptNo());
        refundVo.setTotalAmount(vo.getTotalAmount());
        refundVo.setRefundMoney(vo.getPayMoney());
        refundVo.setPayType(vo.getPayType() + "");
        return refundVo;
    }

    @Override
    public ResultDto add(PayOrderVo payOrderVo) {
//在新增订单时，需要先访问远程接口：然后得到
//        PatientRegisterBudgetVo vo = new PatientRegisterBudgetVo();
//        vo.setPatId(payOrderVo.getPatId());
//        vo.setDeptCode(payOrderVo.getDepartmentCode());
//        vo.setDeptName(payOrderVo.getDepartmentName());
//        vo.setDoctorCode(payOrderVo.getDoctorCode());
//        vo.setDoctorName(payOrderVo.getDoctorName());
//        vo.setRegType(payOrderVo.getRegType());
//        vo.setSchNo(payOrderVo.getSchNo());
//        vo.setDeductAccountType(payOrderVo.getDeductAccountType());
//        vo.setSettleType(payOrderVo.getSettleType());
//        vo.setReserveSortNo(payOrderVo.getReserveSortNo());
//        vo.setPreRegDate(payOrderVo.getVisitTime());
//        vo.setDiscountMoney(payOrderVo.getDiscountMoney());
//        vo.setRegCampus(payOrderVo.getCampusName());
//        vo.setOperatorDeptCode(payOrderVo.getDepartmentCode());
//        JSONObject jsonObject = HttpTool.postJson("stt_0001", vo);
//        Object result = jsonObject.get("result");
//        if (result != null && !"[]".equals(result)) {
//            List<PatientRegisterBudgetDto> list = JSONArray.parseArray(result.toString(), PatientRegisterBudgetDto.class);
//            if (list.size() > 0) {
//                PatientRegisterBudgetDto dto = list.get(0);
//                payOrderVo.setRegId(dto.getRegId());
//                payOrderVo.setReceiptNo(dto.getReceiptNo());
//                payOrderVo.setTotalAmount(dto.getTotalAmount());
//                payOrderVo.setSelfPayMoney(dto.getSelfPayMoney());
//                payOrderVo.setMedPay(dto.getMedPay());
//                payOrderVo.setDiscountMoney(dto.getDiscountMoney());
//                payOrderVo.setAccountPay(dto.getAccountPay());
//                payOrderVo.setAccountBalance(dto.getAccountBalance());
//                payOrderVo.setAmountPayable(dto.getAmountPayable());
//            } else {
//                return ResultDto.data("挂号未成功", jsonObject);
//            }
//        } else {
////            return ResultDto.data("挂号未成功", jsonObject);
//        }
        PayOrderEntity entity = JSONCopy.copy(payOrderVo, PayOrderEntity.class);
        entity.setPayMoney(NumberTool.strToMoney(payOrderVo.getPayMoney()));
<<<<<<< HEAD
=======
        entity.setTotalAmount(NumberTool.strToMoney(payOrderVo.getTotalAmount()));
        entity.setSelfPayMoney(NumberTool.strToMoney(payOrderVo.getSelfPayMoney()));
        entity.setMedPay(NumberTool.strToMoney(payOrderVo.getMedPay()));
        entity.setAccountPay(NumberTool.strToMoney(payOrderVo.getAccountPay()));
        entity.setAccountBalance(NumberTool.strToMoney(payOrderVo.getAccountBalance()));
        entity.setAmountPayable(NumberTool.strToMoney(payOrderVo.getAmountPayable()));
>>>>>>> f2106939b942a7ac2c3470910120a35364fbfaac
        entity.setCreateTime(DateTool.format());
        entity.setOrderTime(DateTool.format());
        payOrderMapper.insert(entity);
        PayOrderEntity en = new PayOrderEntity();
        en.setOpenId(en.getOpenId());
        en.setOrderBy("id desc");
        en.setPage(1);
        en.setSize(1);
        return ResultDto.data(payOrderMapper.select(en));
    }

    @Override
    public ResultDto update(PayOrderVo payOrderVo) {
//先结算，在修改
//        PatientRegisterSettlementVo vo = getPatientRegisterSettlementVo(payOrderVo);
//        JSONObject jsonObject = HttpTool.postJson("stt_0002", vo);
//        Object result = jsonObject.get("result");
        PayOrderEntity entity = JSONCopy.copy(payOrderVo, PayOrderEntity.class);
//        if (result != null && !"[]".equals(result)) {
//            List<PatientRegisterSettlementDto> list = JSONArray.parseArray(result.toString(), PatientRegisterSettlementDto.class);
//            if (list.size() == 0) {
//                return ResultDto.data("挂号结算未成功", jsonObject);
//            }
//        } else {
//            return ResultDto.data("挂号结算未成功", jsonObject);
//        }
        entity.setPayMoney(NumberTool.strToMoney(payOrderVo.getPayMoney()));
<<<<<<< HEAD
=======
        entity.setTotalAmount(NumberTool.strToMoney(payOrderVo.getTotalAmount()));
        entity.setSelfPayMoney(NumberTool.strToMoney(payOrderVo.getSelfPayMoney()));
        entity.setMedPay(NumberTool.strToMoney(payOrderVo.getMedPay()));
        entity.setAccountPay(NumberTool.strToMoney(payOrderVo.getAccountPay()));
        entity.setAccountBalance(NumberTool.strToMoney(payOrderVo.getAccountBalance()));
        entity.setAmountPayable(NumberTool.strToMoney(payOrderVo.getAmountPayable()));
>>>>>>> f2106939b942a7ac2c3470910120a35364fbfaac
        entity.setPayTime(DateTool.format());
        return ResultDto.data(payOrderMapper.updateById(entity));
    }

    /**
     * 将前端传递过来的数据封装成挂号结算数据
     *
     * @param payOrderVo
     * @return
     */
    private PatientRegisterSettlementVo getPatientRegisterSettlementVo(PayOrderVo payOrderVo) {
        PatientRegisterSettlementVo vo = new PatientRegisterSettlementVo();
        vo.setPatId(payOrderVo.getPatId());
        vo.setRegId(payOrderVo.getRegId());
        vo.setReceiptNo(payOrderVo.getReceiptNo());
        vo.setTotalAmount(payOrderVo.getTotalAmount());
        vo.setAmountPayable(payOrderVo.getAmountPayable());
        vo.setPayType(payOrderVo.getPayType());
//        如果是聚合支付或银行支付必填，1中国银行2农业银行3工商银行4建设银行
//        vo.setBank(null);
        vo.setPayChannel(payOrderVo.getPayChannel());
        vo.setAccountNo(payOrderVo.getPatId());
        vo.setPayMoney(payOrderVo.getPayMoney());
        vo.setPaySerialNo(payOrderVo.getPaySerialNo());
        vo.setDeductAccountType(payOrderVo.getDeductAccountType());
        vo.setSelfSettType(payOrderVo.getSettleType());
        vo.setReserveSortNo(payOrderVo.getReserveSortNo());
        vo.setSchNo(payOrderVo.getSchNo());
        vo.setPayTime(DateTool.format());
        vo.setPlatformNo(payOrderVo.getPlatformNo());
        vo.setDiscountMoney(payOrderVo.getDiscountMoney());
        vo.setOrderId(payOrderVo.getPayOrderNo());
//        0，非急诊；1，急诊；为null则非急诊
//        vo.setEmergencyMark();
        vo.setDeptCode(payOrderVo.getDepartmentCode());
        vo.setDoctorCode(payOrderVo.getDoctorCode());
        return vo;
    }

    @Override
    public ResultDto delete(int id) {
        return ResultDto.data(payOrderMapper.deleteById(id));
    }


    @Override
    public ResultDto status(int id) {
        return ResultDto.data(payOrderMapper.status(id));
    }
}
